package com.example.newinfinity.Account.MyWorks

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.HardwareRenderer
import android.graphics.PixelFormat
import android.graphics.RenderEffect
import android.graphics.RenderNode
import android.graphics.Shader
import android.hardware.HardwareBuffer
import android.media.ImageReader
import android.os.Build
import androidx.annotation.RequiresApi

object BlurImageUtil {
    /**
     * 将指定路径的图片虚化并返回虚化后的 Bitmap。
     * @param path 图片文件的路径
     * @param radius 虚化半径
     * @return 虚化后的 Bitmap
     */
    fun blurImageFromPath(path: String, radius: Float): Bitmap {
        val bitmap = BitmapFactory.decodeFile(path) ?: throw IllegalArgumentException("无法从路径解码图片: $path")
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            blurWithRenderEffect(bitmap, radius)
        } else {
            val intRadius = radius.toInt().coerceIn(1, 25) // 限制半径范围以避免性能问题
            blurWithSoftware(bitmap, intRadius)
        }
    }

    /**
     * 使用 RenderEffect 进行硬件加速虚化（API 31+）。
     */
    @RequiresApi(Build.VERSION_CODES.S)
    private fun blurWithRenderEffect(bitmap: Bitmap, radius: Float): Bitmap {
        val imageReader = ImageReader.newInstance(
            bitmap.width, bitmap.height,
            PixelFormat.RGBA_8888, 1,
            HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE or HardwareBuffer.USAGE_GPU_COLOR_OUTPUT
        )
        val renderNode = RenderNode("BlurEffect")
        val hardwareRenderer = HardwareRenderer()
        hardwareRenderer.setSurface(imageReader.surface)
        hardwareRenderer.setContentRoot(renderNode)
        renderNode.setPosition(0, 0, imageReader.width, imageReader.height)
        val blurRenderEffect = RenderEffect.createBlurEffect(radius, radius, Shader.TileMode.MIRROR)
        renderNode.setRenderEffect(blurRenderEffect)
        val renderCanvas = renderNode.beginRecording()
        renderCanvas.drawBitmap(bitmap, 0f, 0f, null)
        renderNode.endRecording()
        hardwareRenderer.createRenderRequest().setWaitForPresent(true).syncAndDraw()
        val image = imageReader.acquireNextImage() ?: throw RuntimeException("无法获取虚化后的图像")
        val hardwareBuffer = image.hardwareBuffer ?: throw RuntimeException("无法获取硬件缓冲区")
        val blurredBitmap = Bitmap.wrapHardwareBuffer(hardwareBuffer, null)
            ?: throw RuntimeException("创建虚化 Bitmap 失败")
        hardwareBuffer.close()
        image.close()
        return blurredBitmap
    }

    /**
     * 使用软件实现的箱形虚化（API < 31）。
     */
    private fun blurWithSoftware(bitmap: Bitmap, radius: Int): Bitmap {
        var blurred = bitmap
        repeat(3) { // 多次应用以模拟高斯虚化效果
            blurred = blurHorizontal(blurred, radius)
            blurred = blurVertical(blurred, radius)
        }
        return blurred
    }

    /**
     * 水平方向的箱形虚化。
     */
    private fun blurHorizontal(bitmap: Bitmap, radius: Int): Bitmap {
        val width = bitmap.width
        val height = bitmap.height
        val pixels = IntArray(width * height)
        bitmap.getPixels(pixels, 0, width, 0, 0, width, height)
        val newPixels = IntArray(width * height)

        for (y in 0 until height) {
            var rSum = 0
            var gSum = 0
            var bSum = 0
            var aSum = 0
            var count = 0

            // 初始化第一个窗口的像素和
            for (i in -radius..radius) {
                val x = i
                if (x >= 0 && x < width) {
                    val color = pixels[y * width + x]
                    rSum += Color.red(color)
                    gSum += Color.green(color)
                    bSum += Color.blue(color)
                    aSum += Color.alpha(color)
                    count++
                }
            }
            newPixels[y * width] = Color.argb(aSum / count, rSum / count, gSum / count, bSum / count)

            // 滑动窗口处理剩余像素
            for (x in 1 until width) {
                val leftX = x - radius - 1
                if (leftX >= 0) {
                    val color = pixels[y * width + leftX]
                    rSum -= Color.red(color)
                    gSum -= Color.green(color)
                    bSum -= Color.blue(color)
                    aSum -= Color.alpha(color)
                    count--
                }
                val rightX = x + radius
                if (rightX < width) {
                    val color = pixels[y * width + rightX]
                    rSum += Color.red(color)
                    gSum += Color.green(color)
                    bSum += Color.blue(color)
                    aSum += Color.alpha(color)
                    count++
                }
                newPixels[y * width + x] = Color.argb(aSum / count, rSum / count, gSum / count, bSum / count)
            }
        }
        return Bitmap.createBitmap(newPixels, width, height, bitmap.config)
    }

    /**
     * 垂直方向的箱形虚化。
     */
    private fun blurVertical(bitmap: Bitmap, radius: Int): Bitmap {
        val width = bitmap.width
        val height = bitmap.height
        val pixels = IntArray(width * height)
        bitmap.getPixels(pixels, 0, width, 0, 0, width, height)
        val newPixels = IntArray(width * height)

        for (x in 0 until width) {
            var rSum = 0
            var gSum = 0
            var bSum = 0
            var aSum = 0
            var count = 0

            // 初始化第一个窗口的像素和
            for (i in -radius..radius) {
                val y = i
                if (y >= 0 && y < height) {
                    val color = pixels[y * width + x]
                    rSum += Color.red(color)
                    gSum += Color.green(color)
                    bSum += Color.blue(color)
                    aSum += Color.alpha(color)
                    count++
                }
            }
            newPixels[x] = Color.argb(aSum / count, rSum / count, gSum / count, bSum / count)

            // 滑动窗口处理剩余像素
            for (y in 1 until height) {
                val topY = y - radius - 1
                if (topY >= 0) {
                    val color = pixels[topY * width + x]
                    rSum -= Color.red(color)
                    gSum -= Color.green(color)
                    bSum -= Color.blue(color)
                    aSum -= Color.alpha(color)
                    count--
                }
                val bottomY = y + radius
                if (bottomY < height) {
                    val color = pixels[bottomY * width + x]
                    rSum += Color.red(color)
                    gSum += Color.green(color)
                    bSum += Color.blue(color)
                    aSum += Color.alpha(color)
                    count++
                }
                newPixels[y * width + x] = Color.argb(aSum / count, rSum / count, gSum / count, bSum / count)
            }
        }
        return Bitmap.createBitmap(newPixels, width, height, bitmap.config)
    }
}